package com.qijian.business.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.business.domain.ProductionDetail;
import com.qijian.business.domain.ProductionDetailSalary;
import com.qijian.business.domain.dto.ProductionDetailDTO;
import com.qijian.business.domain.query.ProductionDetailQuery;
import com.qijian.business.domain.vo.ProductionDetailVo;
import com.qijian.business.domain.query.ProductionDetailQuery;
import com.qijian.business.domain.query.ProductionDetailSalaryQuery;
import com.qijian.business.domain.vo.ProductionDetailSalaryVo;
import com.qijian.business.domain.vo.ProductionDetailVo;
import com.qijian.business.mapper.ProductionDetailMapper;
import com.qijian.business.mapper.ProductionDetailSalaryMapper;
import com.qijian.business.service.IProductionDetailSalaryService;
import com.qijian.business.service.IProductionDetailService;
import com.qijian.common.utils.SecurityUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.maindata.domain.SdInventory;
import com.qijian.maindata.domain.query.SdInventoryQuery;
import com.qijian.maindata.service.ISdInventoryService;
import com.qijian.production.domain.ScWorkOrderDetail;
import com.qijian.production.domain.query.ScWorkOrderQuery;
import com.qijian.production.domain.vo.ScWorkOrderVo;
import com.qijian.production.service.IScWorkOrderDetailService;
import com.qijian.production.service.IScWorkOrderService;
import com.qijian.quality.domain.InspectionResultRecord;
import com.qijian.quality.domain.InspectionResultRecordDetail;
import com.qijian.quality.domain.vo.InspectionResultRecordDetailVo;
import com.qijian.quality.domain.vo.InspectionResultRecordVo;
import com.qijian.quality.service.IInspectionResultRecordDetailService;
import com.qijian.quality.service.IInspectionResultRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 报工Service业务层处理
 *
 * @author qijian
 * @date 2025-03-25
 */
@Service
@RequiredArgsConstructor
public class ProductionDetailServiceImpl extends ServiceImpl<ProductionDetailMapper, ProductionDetail> implements IProductionDetailService {

    private final ProductionDetailMapper productionDetailMapper;

    private final ISdInventoryService sdInventoryService;

    private final IScWorkOrderService scWorkOrderService;

    private final IInspectionResultRecordService inspectionResultRecordService;

    private final IInspectionResultRecordDetailService inspectionResultRecordDetailService;

    private final IProductionDetailSalaryService productionDetailSalaryService;

    private final IScWorkOrderDetailService scWorkOrderDetailService;

    private final ProductionDetailSalaryMapper productionDetailSalaryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveProductionDetail(ProductionDetailDTO productionDetailDTO) {
        Long workOrderId = productionDetailDTO.getWorkOrderId();
        if (workOrderId == null) {
            throw new RuntimeException("本次报工未关联工单，请刷新后重试！");
        }
        Long fmProcessId = productionDetailDTO.getFmProcessId();
        Integer sort = productionDetailDTO.getSort();
        if (fmProcessId == null || sort == null) {
            throw new RuntimeException("请选择要报工的工序！");
        }

        /*Long eqpId = productionDetailDTO.getEqpId();
        if (eqpId == null) {
            throw new RuntimeException("请选择设备！");
        }*/

        //报工数量
        BigDecimal finishQty = productionDetailDTO.getFinishQty();
        if (finishQty == null || BigDecimal.ZERO.compareTo(finishQty) >= 0) {
            throw new RuntimeException("报工数量必须大于0");
        }
        //不合格量
        BigDecimal badNumber = productionDetailDTO.getBadNumber();
        if (badNumber == null) {
            badNumber = BigDecimal.ZERO;
        }
        if (BigDecimal.ZERO.compareTo(badNumber) > 0) {
            throw new RuntimeException("不合格数量必须大于0");
        }

        BigDecimal sumQty = finishQty.add(badNumber);

        //这里查询到具体的工单数据，看一下是否存在上一道工序。
        ScWorkOrderQuery workOrderQuery = new ScWorkOrderQuery();
        workOrderQuery.setId(workOrderId);
        workOrderQuery.setFmProcessId(fmProcessId);
        workOrderQuery.setSort(sort);
        ScWorkOrderVo workOrderData = scWorkOrderService.getOrderDetailDataByQuery(workOrderQuery);
        if (workOrderData == null) {
            throw new RuntimeException("工单不存在，请刷新重试！");
        }

        Integer afterSort = workOrderData.getAfterSort();
        //是否存在上一道工序
        boolean afterProcess = false;
        Long afterProcessId = workOrderData.getAfterProcessId();
        BigDecimal afterProportion = workOrderData.getAfterProportion();
        if (afterProcessId != null) {
            afterProcess = true;
            if (afterProportion == null || afterProportion.compareTo(BigDecimal.ZERO) == 0) {
                //比例没配置的时候直接配置成1
                afterProportion = BigDecimal.ONE;
            }
        }
        /*
         * 定义：原料状态是1；工序报工的料状态是2；入库的库存料是3；
         */
        /*
         * 1、检查是否存在上一道工序
         *      1、存在上一道工序
         *          1、减上一道工序的库存数量；上一道工序的需要扣减库存数量 = 上一道工序的配比*本次的报工数量
         *      2、不存在上一道工序
         *          1、查询是否存在子级工单，
         *              1、存在的话，就扣减子级工单的料，多个子级工单，就分别去扣减。扣减数量 = 子级工单配比*本次的报工数量
         *              2、不存在的话，就扣减需求料
         */
        if (afterProcess) {//存在上一道工序
            //查询出上一道工序的库存量
            SdInventoryQuery sdInventoryQuery = new SdInventoryQuery();
            sdInventoryQuery.setFmProcessId(afterProcessId);
            sdInventoryQuery.setFmProcessSort(afterSort);
            sdInventoryQuery.setWorkOrderId(workOrderId);
            sdInventoryQuery.setStatus("2");
            SdInventory afterInventory = sdInventoryService.getOne(WhereEntityTool.invoke(sdInventoryQuery));
            if (afterInventory == null) {
                afterInventory = new SdInventory();
            }
            if (afterInventory.getQty() == null) {
                afterInventory.setQty(BigDecimal.ZERO);
            }

//          扣减库存数量 = 上一道工序的配比*本次的报工数量
            BigDecimal deductAfterQty = sumQty.multiply(afterProportion);
            BigDecimal afterInventoryQty = afterInventory.getQty();
            if (deductAfterQty.compareTo(afterInventoryQty) > 0) {
                throw new RuntimeException("可报工量不足，剩余可报工量为：" + afterInventoryQty);
            }

            afterInventory.setQty(afterInventory.getQty().subtract(deductAfterQty));
            sdInventoryService.updateById(afterInventory);
        } else { //不存在上一道工序
            //查询是否存在子级工单
            List<ScWorkOrderVo> childWorkOrderList = scWorkOrderService.getChildWorkOrder(workOrderId);

            List<SdInventory> editSdInventoryList = new ArrayList<>();
            if (childWorkOrderList != null && childWorkOrderList.size() > 0) {//存在子级工单\
                List<Long> childWorkOrderIdList = childWorkOrderList.stream().map(ScWorkOrderVo::getChildWorkOrderId).toList();
                SdInventoryQuery sdInventoryQuery = new SdInventoryQuery();
                sdInventoryQuery.setWorkOrderIds(childWorkOrderIdList);
                sdInventoryQuery.setStatus("3");
                List<SdInventory> childSdInventoryList = sdInventoryService.list(WhereEntityTool.invoke(sdInventoryQuery));
                Map<Long, SdInventory> childSdInventoryMap =
                        childSdInventoryList.stream().collect(Collectors.toMap(SdInventory::getWorkOrderId, e -> e));

                for (ScWorkOrderVo childWorkOrderVo : childWorkOrderList) {
                    //拿到配比
                    BigDecimal childProportion = childWorkOrderVo.getChildProportion();
                    if (childProportion == null || childProportion.compareTo(BigDecimal.ZERO) == 0) {
                        childProportion = BigDecimal.ONE;
                    }
                    //拿到需要扣减的数量
                    BigDecimal deductChildQty = sumQty.multiply(childProportion);

                    Long childWorkOrderId = childWorkOrderVo.getChildWorkOrderId();
                    String childItemName = childWorkOrderVo.getChildItemName();
                    SdInventory childSdInventory = childSdInventoryMap.get(childWorkOrderId);
                    if (childSdInventory == null || deductChildQty.compareTo(childSdInventory.getQty()) > 0) {
                        BigDecimal childSdInventoryQty = BigDecimal.ZERO;
                        if (childSdInventory != null) {
                            childSdInventoryQty = childSdInventory.getQty();
                        }
                        throw new RuntimeException("子级物料：" + childItemName + "数量不足,剩余数量为：" + childSdInventoryQty);
                    }
                    childSdInventory.setQty(childSdInventory.getQty().subtract(deductChildQty));
                    editSdInventoryList.add(childSdInventory);
                }
            } else {//不存在子级工单，去查询配置的料
                //查询是否存在需求料
                Long workOrderDetailId = workOrderData.getWorkOrderDetailId();
                List<ScWorkOrderVo> needWorkOrderList = scWorkOrderService.getNeedItem(workOrderId, workOrderDetailId);
                if (needWorkOrderList == null || needWorkOrderList.size() < 1) {
                    throw new RuntimeException("未配置原材料，请先配置原材料！");
                }
                List<Long> needItemIds = needWorkOrderList.stream().map(ScWorkOrderVo::getNeedItemId).collect(Collectors.toList());
                SdInventoryQuery sdInventoryQuery = new SdInventoryQuery();
                sdInventoryQuery.setItemIds(needItemIds);
                sdInventoryQuery.setStatus("1");
                List<SdInventory> needSdInventoryList = sdInventoryService.list(WhereEntityTool.invoke(sdInventoryQuery));
                //现在没有原料的具体格式，暂时定一个物料一个库存。后面再改
                Map<Long, SdInventory> needSdInventoryMap = needSdInventoryList.stream().collect(Collectors.toMap(SdInventory::getItemId, e -> e));

                for (ScWorkOrderVo scWorkOrderVo : needWorkOrderList) {
                    Long needItemId = scWorkOrderVo.getNeedItemId();
                    String needItemName = scWorkOrderVo.getNeedItemName();
                    BigDecimal needQty = scWorkOrderVo.getNeedQty();
                    //拿到需要扣减的数量
                    BigDecimal deductNeedQty = sumQty.multiply(needQty);

                    SdInventory needSdInventory = needSdInventoryMap.get(needItemId);
                    BigDecimal needSdInventoryQty = BigDecimal.ZERO;
                    if (needSdInventory == null || deductNeedQty.compareTo(needSdInventory.getQty()) > 0) {
                        if (needSdInventory != null) {
                            needSdInventoryQty = needSdInventory.getQty();
                        }
                        throw new RuntimeException("原料：" + needItemName + "库存不足支撑本次报工，需求:" + deductNeedQty + ",持有库存:" + needSdInventoryQty);
                    }
                    needSdInventory.setQty(needSdInventory.getQty().subtract(deductNeedQty));
                    editSdInventoryList.add(needSdInventory);
                }
            }
            sdInventoryService.updateBatchById(editSdInventoryList);
        }

        //保存本道工序的报工数据
        ProductionDetail productionDetail = new ProductionDetail();
        BeanUtils.copyProperties(productionDetailDTO, productionDetail);
        productionDetail.setWorkOrderDetailId(workOrderData.getWorkOrderDetailId());
        productionDetail.setUserId(SecurityUtils.getUserId());
        productionDetail.setUserName(SecurityUtils.getNickName());
        this.save(productionDetail);

        BigDecimal workCost = workOrderData.getWorkCost();
        if (workCost == null) {
            workCost = BigDecimal.ONE;
        }
        //保存报工工资数据
        saveProductionDetailSalary(fmProcessId, sort, finishQty, badNumber, workOrderData, productionDetail, workCost);

        //保存质检数据
        saveInspectionData(productionDetailDTO, productionDetail);


        ScWorkOrderVo scWorkOrderVo = scWorkOrderService.getMaxSortData(workOrderId);
        Integer maxSort = scWorkOrderVo.getMaxSort();
        if (Objects.equals(maxSort, sort)) {
            //证明是最后一道工序，直接入库工单产品
            Long itemId = workOrderData.getItemId();
            SdInventoryQuery sdInventoryQuery = new SdInventoryQuery();
            sdInventoryQuery.setWorkOrderId(productionDetail.getWorkOrderId());
            sdInventoryQuery.setItemId(itemId);
            sdInventoryQuery.setStatus("3");
            SdInventory sdInventory = sdInventoryService.getOne(WhereEntityTool.invoke(sdInventoryQuery));
            if (sdInventory == null) {
                sdInventory = new SdInventory();
                sdInventory.setWorkOrderId(productionDetail.getWorkOrderId());
                sdInventory.setItemId(itemId);
                sdInventory.setItemCode(workOrderData.getItemCode());
                sdInventory.setItemName(workOrderData.getItemName());
                sdInventory.setQty(BigDecimal.ZERO);
                sdInventory.setStatus("3");
            }
            sdInventory.setQty(sdInventory.getQty().add(finishQty));
            sdInventoryService.saveOrUpdate(sdInventory);
        } else {
            //保存本道工序的库存数量
            SdInventoryQuery sdInventoryQuery = new SdInventoryQuery();
            sdInventoryQuery.setWorkOrderId(productionDetail.getWorkOrderId());
            sdInventoryQuery.setFmProcessId(productionDetail.getFmProcessId());
            sdInventoryQuery.setFmProcessSort(productionDetail.getSort());
            sdInventoryQuery.setStatus("2");
            SdInventory sdInventory = sdInventoryService.getOne(WhereEntityTool.invoke(sdInventoryQuery));
            if (sdInventory == null) {
                sdInventory = new SdInventory();
                sdInventory.setFmProcessSort(productionDetail.getSort());
                sdInventory.setWorkOrderId(productionDetail.getWorkOrderId());
                sdInventory.setFmProcessId(productionDetail.getFmProcessId());
                sdInventory.setQty(BigDecimal.ZERO);
                sdInventory.setStatus("2");
            }
            sdInventory.setQty(sdInventory.getQty().add(finishQty));
            sdInventoryService.saveOrUpdate(sdInventory);
        }
        BigDecimal producedQty = workOrderData.getProducedQty();
        if (producedQty == null) {
            producedQty = BigDecimal.ZERO;
        }
        ScWorkOrderDetail editScWorkOrderDetail = new ScWorkOrderDetail();
        editScWorkOrderDetail.setId(workOrderData.getWorkOrderDetailId());
        editScWorkOrderDetail.setProducedQty(producedQty.add(finishQty));
        return scWorkOrderDetailService.updateById(editScWorkOrderDetail);
    }

    @Override
    public Page<ProductionDetailVo> pageVo(Page<ProductionDetail> page, ProductionDetailQuery query) {
        return baseMapper.getPageVo(page, WhereEntityTool.invoke(query));
    }

    @Override
    public Page<ProductionDetailVo> pageListDay(Page<ProductionDetail> page, ProductionDetailQuery queryWrapper) {
        // 获取当天的日期
        LocalDate today = LocalDate.now();

        // 转换为 LocalDateTime，开始时间为当天的 00:00:00
        LocalDateTime startOfDay = today.atStartOfDay();

        // 结束时间为当天的 23:59:59.999999999（或简化为下一天的 00:00:00，但不包含）
        LocalDateTime endOfDay = today.plusDays(1).atStartOfDay(); // 或者使用 LocalTime.MAX 来构造当天的结束时间，但这里用下一天开始更直观

        Long userId = SecurityUtils.getUserId();
        if(queryWrapper.getDate()==null){
            if(queryWrapper.getStartOfDay()==null){
                queryWrapper.setStartOfDay(startOfDay);
            }if(queryWrapper.getEndOfDay()==null){
                queryWrapper.setEndOfDay(endOfDay);
            }
        }
        queryWrapper.setUserIdSalary(userId);
        Page<ProductionDetailVo> productionDetailVoPage = baseMapper.pageListSalary(page, WhereEntityTool.invoke(queryWrapper));
        return productionDetailVoPage;
    }

    @Override
    public Page<ProductionDetailVo> pageListMoon(Page<ProductionDetail> page,  ProductionDetailQuery queryWrapper) {
        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 获取当月的第一天
        LocalDate firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
        // 转换为 LocalDateTime，开始时间为当月第一天的 00:00:00
        LocalDateTime startOfDay = firstDayOfMonth.atStartOfDay();

        // 获取当月的最后一天
        LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
        // 转换为 LocalDateTime，结束时间为当月最后一天的 23:59:59.999...
        // 但由于我们使用 < 比较，所以实际上可以设置为下一天 00:00:00 之前，这里为了精确到当天结束，我们用当天23:59:59或直接用日期范围表示
        LocalDateTime endOfDay = lastDayOfMonth.atTime(LocalTime.MAX); // 或者使用下月第一天0点作为排除条件，但这里用MAX更精确表示当天结束
        if(queryWrapper.getStartOfDay()==null){
            queryWrapper.setStartOfDay(startOfDay);
        }if(queryWrapper.getEndOfDay()==null){
            queryWrapper.setEndOfDay(endOfDay);
        }
        Long userId = SecurityUtils.getUserId();
        queryWrapper.setUserIdSalary(userId);
        Page<ProductionDetailVo> productionDetailVoPage = baseMapper.pageListMoonSalary(page, WhereEntityTool.invoke(queryWrapper));
        List<ProductionDetailVo> records = productionDetailVoPage.getRecords();
        if(records!=null && records.size()>0){
            for (ProductionDetailVo record : records) {
                String createTime = record.getWorkTime();
                if(createTime!=null){
                    LocalDate date = LocalDate.parse(createTime);
                    // 获取星期几
                    DayOfWeek dayOfWeek = date.getDayOfWeek();
                    String chineseDayOfWeek = getChineseDayOfWeek(dayOfWeek);
                    record.setDayOfWeek(chineseDayOfWeek);
                    List<ProductionDetailVo> productionDetailVoList = baseMapper.pageListMoonSalary2(createTime,userId);
                    if(productionDetailVoList!=null && productionDetailVoList.size()>0){
                        record.setProductionDetailVoList(productionDetailVoList);
                    }
                }

            }
        }
        return productionDetailVoPage;
    }

    @Override
    public List<ProductionDetailSalaryVo> listMoonSum(ProductionDetailSalaryQuery queryWrapper) {
        List<ProductionDetailSalaryVo> productionDetailSalaryVos = productionDetailSalaryMapper.countUserSalary(SecurityUtils.getUserId());
        // 获取当前年月
        YearMonth currentYearMonth = YearMonth.now();
        // 获取当月天数
        int daysInMonth = currentYearMonth.lengthOfMonth();
        List<ProductionDetailSalaryVo> productionDetailSalaryVos1 = new ArrayList<>();
        for (int i = 1; i < daysInMonth+1; i++) {
            ProductionDetailSalaryVo productionDetailSalaryVo = new ProductionDetailSalaryVo();
            if(productionDetailSalaryVos!=null && productionDetailSalaryVos.size()>0){
                boolean a = true;
                for (ProductionDetailSalaryVo detailSalaryVo : productionDetailSalaryVos) {
                    if(i == detailSalaryVo.getDay()){
                        detailSalaryVo.setMonth(currentYearMonth+"");
                        productionDetailSalaryVos1.add(detailSalaryVo);
                        a =false;
                        break;
                    }
                }
                if(a){
                    productionDetailSalaryVo.setMonth(currentYearMonth+"");
                    productionDetailSalaryVo.setDay(i);
                    productionDetailSalaryVo.setUserSalary(BigDecimal.ZERO);
                    productionDetailSalaryVos1.add(productionDetailSalaryVo);
                }
            }else {
                productionDetailSalaryVo.setMonth(currentYearMonth+"");
                productionDetailSalaryVo.setDay(i);
                productionDetailSalaryVo.setUserSalary(BigDecimal.ZERO);
                productionDetailSalaryVos1.add(productionDetailSalaryVo);
            }
        }
        return productionDetailSalaryVos1;
    }

    @Override
    public List<ProductionDetailSalaryVo> listMoonSalary(ProductionDetailSalaryQuery queryWrapper) {
        return productionDetailSalaryMapper.listMoonSalary(SecurityUtils.getUserId());
    }

    @Override
    public List<ProductionDetailSalary> listDaySum(ProductionDetailSalaryQuery query) {
        Long userId = SecurityUtils.getUserId();
        query.setUserId(userId);
        if(query.getDate()==null){
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            query.setDate(currentDate+"");
        }
        List<ProductionDetailSalary> productionDetailSalaries = productionDetailSalaryMapper.countUserDaySalary(WhereEntityTool.invoke(query));
        List<ProductionDetailSalary> objects = new ArrayList<>();
        if (productionDetailSalaries!=null && productionDetailSalaries.size()==1){
            for (ProductionDetailSalary productionDetailSalary : productionDetailSalaries) {
                if(productionDetailSalary.getTeamLeaderCheck()){
                    ProductionDetailSalary productionDetailSalary1 = new ProductionDetailSalary();
                    productionDetailSalary1.setUserSalary(BigDecimal.ZERO);
                    productionDetailSalary1.setTeamLeaderCheck(false);
                    objects.add(productionDetailSalary1);
                }
                objects.add(productionDetailSalary);
            }
        }else {
            return  productionDetailSalaries;
        }
        return  objects;
    }

    private void saveProductionDetailSalary(Long fmProcessId, Integer sort, BigDecimal finishQty, BigDecimal badNumber, ScWorkOrderVo workOrderData, ProductionDetail productionDetail, BigDecimal workCost) {
        ProductionDetailSalary productionDetailSalary = new ProductionDetailSalary();
        productionDetailSalary.setProductionDetailId(productionDetail.getId());
        productionDetailSalary.setUserId(SecurityUtils.getUserId());
        productionDetailSalary.setUserName(SecurityUtils.getNickName());
        productionDetailSalary.setUserSalary(finishQty.multiply(workCost));
        productionDetailSalary.setCurWorkCost(workCost);
        productionDetailSalary.setFinishQty(finishQty);
        productionDetailSalary.setBadNumber(badNumber);
        productionDetailSalary.setTeamLeaderCheck(false);
        productionDetailSalary.setCheckTime(null);
        productionDetailSalary.setFmProcessId(fmProcessId);
        productionDetailSalary.setProcessName(workOrderData.getProcessName());
        productionDetailSalary.setSort(sort);
        productionDetailSalaryService.save(productionDetailSalary);
    }

    /**
     * 保存质检数据
     * @param productionDetailDTO
     * @param productionDetail
     */
    private void saveInspectionData(ProductionDetailDTO productionDetailDTO, ProductionDetail productionDetail) {
        //获取当前报工的检验内容
        List<InspectionResultRecordDetailVo> detailVoList = productionDetailDTO.getDetailVoList();

        List<InspectionResultRecordDetail> saveDetailList = new ArrayList<>();
        if (detailVoList != null && detailVoList.size() > 0) {
            //总表
            InspectionResultRecord inspectionResultRecord = new InspectionResultRecordVo();
            // 自检
            inspectionResultRecord.setSourceId(productionDetail.getId());
            inspectionResultRecord.setSourceType(ProductionDetail.class.getSimpleName());
            inspectionResultRecord.setProcessName(productionDetail.getProcessName());
            Long inspectionSchemeId = null;


            boolean isQualified = true;
            for (InspectionResultRecordDetailVo detailVo : detailVoList) {
                if (inspectionSchemeId == null) {
                    inspectionSchemeId = detailVo.getSchemeId();
                }

                Boolean isText = detailVo.getIsText();
                if (isText) {//填值
                    String actualValue = detailVo.getActualValue();
                    String maxValue = detailVo.getMaxValue();
                    String minValue = detailVo.getMinValue();
                    if (isQualified) {
                        if (new BigDecimal(actualValue).compareTo(new BigDecimal(maxValue)) > 0 ||
                                new BigDecimal(minValue).compareTo(new BigDecimal(actualValue)) > 0) {
                            detailVo.setIsQualified(false);
                            isQualified = false;
                        }
                    }
                }
                InspectionResultRecordDetail inspectionResultRecordDetail = new InspectionResultRecordDetail();
                BeanUtils.copyProperties(detailVo, inspectionResultRecordDetail);
                saveDetailList.add(inspectionResultRecordDetail);
            }

            inspectionResultRecord.setInspectionSchemeId(inspectionSchemeId);
            inspectionResultRecord.setIsQualified(isQualified);
            inspectionResultRecordService.save(inspectionResultRecord);
            for (InspectionResultRecordDetail detail : saveDetailList) {
                detail.setMainId(inspectionResultRecord.getId());
            }
            inspectionResultRecordDetailService.saveBatch(saveDetailList);
        }
    }

    // 将 DayOfWeek 转换为中文表示
    private static String getChineseDayOfWeek(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY:
                return "周一";
            case TUESDAY:
                return "周二";
            case WEDNESDAY:
                return "周三";
            case THURSDAY:
                return "周四";
            case FRIDAY:
                return "周五";
            case SATURDAY:
                return "周六";
            case SUNDAY:
                return "周日";
            default:
                return "";
        }
    }
}
